import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
// import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
import { staticRoutes } from '@/router/routes'
import userInfoApi,{type userInfoModel} from '@/api/userInfo';
import type { RouteRecordRaw } from "vue-router";
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
interface UserInfoState {
  token: string,
  userInfo: userInfoModel,
  menuRoutes: RouteRecordRaw[];
}

const initUserInfo = () => ({
  avatar: '',
  name: '',
  buttons: [],
  roles: [],
  routes: []
})


export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    userInfo: initUserInfo(),
    menuRoutes: []
  }),

  actions: {
    //调用api里面的接口
    async login(username: string, password: string) {
      try {
        let result = await userInfoApi.login({ username, password })
        console.log(result);
        //在localStorage中获取token
        setToken(result.token);//这里飘红的原因是没有返回值的类型
        //将token存到action中
        this.token = result.token;
      } catch (error) {
        ElMessage.error('登录界面跳转失败，请重试');
        return Promise.reject(error);
      }
    },
    async getInfo() {
      try {
        let result = await userInfoApi.getInfo();
        //存储个人信息
        this.userInfo = result;
        // 注意: menuRoutes 是侧边菜单栏的数据
        // 这里需要获取个人信息的时候,同时拿到个人的权限信息,在这个位置进行过滤才能希显示侧边菜单栏
        // 这里目前写死即可,到最后我们会过来做权限控制
        this.menuRoutes = staticRoutes // 目前写死
      } catch (error) {
        ElMessage.error('获取个人信息失败，请重试');
        return Promise.reject(error);
      }
    },
    async reset() {
      try {
        await userInfoApi.logout();
      } catch (error) {
        console.log('登录失败',error);
      } finally {
        // 删除local中保存的token
        removeToken()
        // 提交重置用户信息的mutation
        this.token = ''
        this.userInfo = initUserInfo();
      }
    },
  },
});
